package org.easy.clickhouse.configuration;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.easy.clickhouse.prop.ClickhouseProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.time.LocalDateTime;

/**
 * @Description:
 * @Author: wxl
 * @CreateTime: 2023/5/4 14:51
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({ClickhouseProperties.class})
public class AutoConfigurationClickHouse {

    @Resource
    private ClickhouseProperties clickhouseProperties;

    @Bean(name = "ckDataSource")
    @ConditionalOnClass(ClickhouseProperties.class)
    public DataSource dataSource () {
        log.info("开始配置CK数据库：{}", LocalDateTime.now());
        HikariConfig hikariConfig = new HikariConfig();
        initHikariConfig(hikariConfig);
        log.info("数据库配置信息：{}", hikariConfig);
        HikariDataSource dataSource = new HikariDataSource(hikariConfig);
        log.info("结束配置CK数据库：{}", LocalDateTime.now());
        return dataSource;
    }

    private void initHikariConfig(HikariConfig hikariConfig){
        hikariConfig.setDriverClassName(clickhouseProperties.getDriverClassName());
        hikariConfig.setJdbcUrl(getUrl());
        hikariConfig.setUsername(clickhouseProperties.getUserName());
        hikariConfig.setPassword(clickhouseProperties.getPassword());
    }

    private String getUrl() {
        String format = "jdbc:clickhouse://%s:%d/%s";
        String url = String.format(format,clickhouseProperties.getHost(),clickhouseProperties.getPort(),clickhouseProperties.getDataBase());
        log.info("数据库地址:{}",url);
        return url;
    }

}
